package cn.itlaobing.eshopmanagement.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.itlaobing.eshopmanagement.entity.Activity;
import cn.itlaobing.eshopmanagement.entity.enums.State;
import cn.itlaobing.eshopmanagement.service.ActivityService;

@Controller
@RequestMapping("/activity")
public class ActivityController extends BaseController{
	@Autowired
	private ActivityService activityService;
	/**
	 * 列表显示所有或动
	 * @param model
	 * @return
	 */
	@GetMapping
	public String index(Model model){
		List<Activity> list=activityService.findBySearchFilter(buildPageRequestSearchFilter());
		model.addAttribute("schedule", list);
		return "/activity/index";
	}
	/**
	 * 查看活动详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/{id}/show")
	public String show(@PathVariable Long id,Model model){
		model.addAttribute("state", State.values());
		model.addAttribute("schedule",activityService.findbyId(id));
		return "/activity/show";
	}
	/**
	 * 添加新的活动内容
	 * @return
	 */
	@GetMapping("/create")
	public String _new(Model model){
		Activity activity=new Activity();
		model.addAttribute("state", State.values());
		model.addAttribute("activity", activity);
		return "/activity/create";
	}
	/**
	 * 添加新的活动信息完成，保存活动信息
	 * @return
	 */
	@PostMapping("/create")
	public String create(@Valid @ModelAttribute Activity activity,
			BindingResult bindResult,Model model,RedirectAttributes redirectAttribute){
		if(bindResult.hasErrors()){
			model.addAttribute("state", State.values());
			return "/activity/create";
		}
		activityService.save(activity);
		redirectAttribute.addFlashAttribute("msg", "添加"+activity.getScheduleName()+"活动成功");
		return "redirect:/activity";
	}
	/**
	 * 删除活动
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
	public Activity delete(@PathVariable Long id){
		Activity activity=activityService.findbyId(id);
		activityService.delete(id);
		return activity;
	}
	
}
